﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BCMS.Forms;
using BCMS.Business.Implementation;
using BCMS.Business.DataContract;
using System.Reflection;
using System.Collections;
using BCMS.Report;
using BCMS.Forms.Report;
using BCMS.FrontEnd.DataContract;
using BCMS.Settings;
using BCMS.Forms.Functions;
using CrystalDecisions.Shared;

namespace BCMS
{
    public partial class frmMain : Form
    {

        #region FormEvents
        public frmMain()
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();

            ArrayList arTmp = new ArrayList();
            for (int i = 0; i < GlobalVars.activeRoles.Length; i++)
            {
                if (GlobalVars.activeRoles[i] == '0')
                {
                    if (i < tabMain.TabPages.Count)
                        arTmp.Add(tabMain.TabPages[i]);
                }
            }
            for (int i = 0; i < arTmp.Count; i++)
            {
                tabMain.TabPages.Remove(arTmp[i] as TabPage);
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            loadTargetList();
            loadKindList();
            loadDetailSuggestion();
            if (GlobalVars.activeUserId.Equals(18))
            {
                xÓADỮLIỆUĐợtPhátHànhToolStripMenuItem.Enabled = true;
                mnDeleteRelease.Enabled = true;
                btnDelete.Enabled = true;
            }

        }

        private void btnClaim_Click(object sender, EventArgs e)
        {
            frmCoupon cpn = new frmCoupon(this, Params.CDate);
            cpn.ShowDialog();
        }

        private void btnRelease_Click(object sender, EventArgs e)
        {
            frmRelease rls = new frmRelease(this);
            rls.ShowDialog();
        }

        private void btnExtend_Click(object sender, EventArgs e)
        {
            frmCouponExtend frmExend = new frmCouponExtend();
            frmExend.ShowDialog();
        }

        private void txtDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter))
                updateReleaseList();
        }

        private void tabMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            DALclient client = new DALclient();
            if (string.IsNullOrEmpty(GlobalVars.activeUser) || string.IsNullOrEmpty(GlobalVars.activeRoles))
                return;
            if (tabMain.SelectedIndex < 0 && tabMain.SelectedIndex >= tabMain.TabPages.Count) return;
            string tabName = tabMain.TabPages[tabMain.SelectedIndex].Name;
            switch (tabName)
            {
                case "tbCoupon":
                    if (GlobalVars.activeRoles[0] != '1')
                    {
                        MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                        int retVal = getNearestRole(0);
                        if (retVal == -1) return;
                        else tabMain.SelectedIndex = retVal;
                    }
                    else
                    {
                        updateCouponsSummary(grvCoupons);
                    }
                    break;
                case "tbRelease":
                    if (GlobalVars.activeRoles[1] != '1')
                    {
                        MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                        int retVal = getNearestRole(1);
                        if (retVal == -1) return;
                        else tabMain.SelectedIndex = retVal;
                    }
                    else
                    {
                        loadDetailSuggestion();
                        loadTargetList();
                        loadKindList();

                        updateReleaseSummary();
                    }
                    break;
                case "tbReport":
                    //resetSummary();
                    if (GlobalVars.activeRoles[2] != '1')
                    {
                        MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                        int retVal = getNearestRole(2);
                        if (retVal == -1) return;
                        else tabMain.SelectedIndex = retVal;
                    }
                    else
                    {

                    }

                    break;
                case "tbAdmin":
                    resetSummary();
                    ToolTip logUser = new ToolTip();
                    logUser.SetToolTip(txtuserLog, Params.HELP_USERLOG);
                    if (GlobalVars.activeRoles[3] != '1')
                    {
                        MessageBox.Show("Bạn không có quyền thực hiện chức năng này");
                        int retVal = getNearestRole(3);
                        if (retVal == -1) return;
                        else tabMain.SelectedIndex = retVal;
                    }
                    else
                        getUserList();

                    break;
                default:
                    break;
            }
        }

        private void txtNumCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                updateCouponsList();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnReport_Click(object sender, EventArgs e)
        {
            updateReportGrid();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F1:
                    goToTab(tbCoupon.Name);
                    return true;
                case Keys.F2:
                    goToTab(tbRelease.Name);
                    return true;
                case Keys.F3:
                    goToTab(tbReport.Name);
                    return true;
                case Keys.F4:
                    goToTab(tbAdmin.Name);
                    return true;
                case Keys.F5:
                    string tabName = tabMain.TabPages[tabMain.SelectedIndex].Name;
                    switch (tabName)
                    {
                        case "tbCoupon":
                            updateCouponsList();
                            updateCouponsSummary(grvCoupons);
                            break;
                        case "tbRelease":
                            updateReleaseList();
                            updateReleaseSummary();
                            break;
                        case "tbReport":
                            updateReportGrid();
                            break;
                    }
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        #region Report

        private void updateReportGrid()
        {
            switch (cbReportKind.SelectedIndex)
            {
                case 0:
                    frmCouponReport totalClaim = new frmCouponReport("TotalClaim", this);
                    totalClaim.ShowDialog();
                    break;
                case 1:
                    frmCouponReport claimByUser = new frmCouponReport("ClaimByUser", this);
                    claimByUser.ShowDialog();
                    break;
                case 2:
                    frmCouponReport expired = new frmCouponReport("Expired", this);
                    expired.ShowDialog();
                    break;
                case 3:
                    frmCouponReport unExpired = new frmCouponReport("UnExpired", this);
                    unExpired.ShowDialog();
                    break;
                case 4:
                    frmCouponReport byReleaseDate = new frmCouponReport("ByReleaseDate", this);
                    byReleaseDate.ShowDialog();
                    break;
                case 5:
                    frmReleaseReport release = new frmReleaseReport("TotalRelease", this);
                    release.ShowDialog();
                    break;
                case 6:
                    frmCouponReport expireDetail = new frmCouponReport("ExpireDetail", this);
                    expireDetail.ShowDialog();
                    break;
                case 7:
                    frmCouponReport unexpiredUnclaim = new frmCouponReport("UnexpireUnclaim", this);
                    unexpiredUnclaim.ShowDialog();
                    break;
                default:
                    GlobalVars.ShowInfo("Hãy chọn một loại báo cáo");
                    break;
            }
        }

        private void setSummaryGridLayout(DataGridView grvSummary)
        {
            grvSummary.Columns["ReleaseId"].HeaderText = "Đợt phát hành";
            grvSummary.Columns["ReleaseId"].DisplayIndex = 0;

            grvSummary.Columns["Value"].HeaderText = "Mệnh giá";
            grvSummary.Columns["Value"].DisplayIndex = 1;
            grvSummary.Columns["Value"].DefaultCellStyle.Format = "N0";

            grvSummary.Columns["Qtty"].HeaderText = "Số lượng";
            grvSummary.Columns["Qtty"].DisplayIndex = 2;
            grvSummary.Columns["Qtty"].DefaultCellStyle.Format = "N0";

            grvSummary.Columns["TotalValue"].HeaderText = "Tổng giá trị";
            grvSummary.Columns["TotalValue"].DisplayIndex = 3;
            grvSummary.Columns["TotalValue"].DefaultCellStyle.Format = "N0";

            grvSummary.Columns["Status"].HeaderText = "Trạng thái";
            grvSummary.Columns["Status"].DisplayIndex = 4;

            grvSummary.Sort(grvSummary.Columns["ReleaseId"], ListSortDirection.Descending);
        }

        private List<SummaryReportUI> buildSummaryByValueSource(List<CouponBrief> summaries, List<ReleaseInfo> releases)
        {
            try
            {
                List<SummaryReportUI> list = new List<SummaryReportUI>();
                foreach (CouponBrief summary in summaries)
                    list.Add(new SummaryReportUI(summary.ParValue,
                                                    string.Empty,
                                                    summary.TotalQtty,
                                                    summary.TotalValue,
                                                    string.Empty));
                return list;
            }
            catch
            {
                return null;
                throw;
            }
        }

        private void cbReportKind_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateReportGrid();
        }

        public void formatCouponBrief(DataGridView grv)
        {
            grv.Columns["ParValue"].HeaderText = "Mệnh giá";
            grv.Columns["ParValue"].DisplayIndex = 1;
            grv.Columns["ParValue"].DefaultCellStyle.Format = "N0";

            grv.Columns["Qtty"].HeaderText = "Số lượng";
            grv.Columns["Qtty"].DisplayIndex = 2;
            grv.Columns["Qtty"].DefaultCellStyle.Format = "N0";
            grv.Columns["Qtty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grv.Columns["TotalValue"].HeaderText = "Giá trị";
            grv.Columns["TotalValue"].DisplayIndex = 3;
            grv.Columns["TotalValue"].DefaultCellStyle.Format = "N0";
            grv.Columns["TotalValue"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grv.Columns["ClaimBy"].Visible = false;
            //grvReport.Columns["ClaimBy"].DisplayIndex = 4;

            grv.Columns["ClaimDate"].Visible = false;
            //grvReport.Columns["ClaimDate"].DisplayIndex = 0;

            grv.Columns["Status"].Visible = false;
        }

        public void updateCouponBriefSummary(DataGridView grv)
        {
            grpStatistic.Visible = true;
            SortableBindingList<CouponBriefUI> cp = grv.DataSource as SortableBindingList<CouponBriefUI>;

            if (cp != null)
            {
                long totalQtty = 0;
                long totalValue = 0;

                foreach (CouponBriefUI item in cp)
                {
                    totalQtty += item.Qtty;
                    totalValue += Convert.ToInt64(item.TotalValue);
                }

                txtTotalQtty.Value = totalQtty;
                txtTotalValue.Value = totalValue;
            }
            else
            {
                txtTotalQtty.Value = 0;
                txtTotalValue.Value = 0;
            }
        }

        #endregion

        #region Admin
        private void btnBackup_Click(object sender, EventArgs e)
        {
            frmSystemBackupAndRestore frm = new frmSystemBackupAndRestore("Backup");
            frm.ShowDialog();
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            frmSystemBackupAndRestore frm = new frmSystemBackupAndRestore("Restore");
            frm.ShowDialog();
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            frmUserAdd frm = new frmUserAdd();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                grvUsers.Rows.Add();
                int index = grvUsers.Rows.Count - 1;
                UserUI user = frm.InsertedUser;
                grvUsers.Rows[index].Cells["ID"].Value = user.ID;
                grvUsers.Rows[index].Cells["UserName"].Value = user.UserName;

            }
            frm.Dispose();
            frm = null;
        }

        private void rolesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int userId = 0;
            if (grvUsers.SelectedCells.Count > 0)
            {
                userId = int.Parse(grvUsers.Rows[grvUsers.SelectedCells[0].RowIndex].Cells["ID"].Value.ToString());
                string username = grvUsers.Rows[grvUsers.SelectedCells[0].RowIndex].Cells["UserName"].Value.ToString();
                frmUserAuthorization frm = new frmUserAuthorization(userId, username);
                frm.ShowDialog();
            }
        }

        private void btnChangePassword_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(GlobalVars.activeUser))
            {
                frmUserResetPassword frm = new frmUserResetPassword(GlobalVars.activeUserId);
                frm.ShowDialog();
            }
        }

        private void ctUsers_Opening(object sender, CancelEventArgs e)
        {
            changePasswordToolStripMenuItem.Enabled = false;
            rolesToolStripMenuItem.Enabled = false;
            uInfoToolStripMenuItem.Enabled = false;
            if (grvUsers.SelectedCells.Count > 0)
            {
                changePasswordToolStripMenuItem.Enabled = true;
                rolesToolStripMenuItem.Enabled = true;
                uInfoToolStripMenuItem.Enabled = true;
            }
        }

        private void txtLogUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter))
            {
                searchLog();
            }
        }

        private void searchLog()
        {
            if (dtFrom.Value.Date > dtTo.Value.Date)
                MessageBox.Show("Khoảng thời gian tìm kiếm không hợp lệ.");

            DALclient client = new DALclient();
            try
            {
                List<LogUI> logs = client.searchLog(txtuserLog.Text, string.Empty,
                                    dtFrom.Value.Date, dtTo.Value.Date.AddDays(1));
                if (logs != null)
                {
                    grvLogs.DataSource = logs;
                }
                else
                {
                    GlobalVars.ShowWarning("Chưa có thao tác trên hệ thống");
                    grvLogs.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError("ERROR: " + ex.Message);
            }
        }

        private void getUserList()
        {
            DALclient client = new DALclient();
            List<UserUI> listUser = client.getAllUsers();
            grvUsers.Rows.Clear();
            for (int i = 0; i < listUser.Count; i++)
            {
                grvUsers.Rows.Add();
                grvUsers.Rows[i].Cells["ID"].Value = listUser[i].ID;
                grvUsers.Rows[i].Cells["UserName"].Value = listUser[i].UserName;
            }
        }

        #region UserContextMenu

        private void addNewUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnAddUser_Click(null, null);
        }

        private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int userId = 0;
            if (grvUsers.SelectedCells.Count > 0)
            {
                userId = int.Parse(grvUsers.Rows[grvUsers.SelectedCells[0].RowIndex].Cells["ID"].Value.ToString());
                frmUserResetPassword frm = new frmUserResetPassword(userId);
                frm.ShowDialog();
            }
        }

        private void uInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int userId = 0;
            if (grvUsers.SelectedCells.Count > 0)
            {
                int rowIndex = grvUsers.SelectedCells[0].RowIndex;
                userId = int.Parse(grvUsers.Rows[rowIndex].Cells["ID"].Value.ToString());
                frmUserUpdate frm = new frmUserUpdate(userId);
                frm.ShowDialog();
            }
        }

        #endregion

        #endregion

        #region Release

        public void updateReleaseList()
        {
            DALclient client = new DALclient();
            List<ReleaseUI> src = client.searchRelease(txtRCode.Text, txtNum.Value,
                                                        txtParValue.Value, (int)cbKind.SelectedValue,
                                                        (int)cbTarget.SelectedValue, txtDetail.Text,
                                                        dtFrom.Value.Date, dtTo.Value.Date.AddDays(1));
            if (src != null)
            {
                SortableBindingList<ReleaseUI> releaseList = new SortableBindingList<ReleaseUI>(src);
                grvReleases.DataSource = releaseList;
                formatReleaseGrid(grvReleases);
            }
            else
                grvReleases.DataSource = null;

            updateReleaseSummary();
        }

        public void formatReleaseGrid(DataGridView grvReleases)
        {
            if (GlobalVars.activeRoles[1] == '0')
                return;

            //grvReleases.Columns["ReleaseId"].Visible = false;
            grvReleases.Columns["Name"].Visible = false;

            grvReleases.Columns["RCode"].DisplayIndex = 0;
            grvReleases.Columns["RCode"].HeaderText = "Series";

            grvReleases.Columns["RLow"].DisplayIndex = 1;
            grvReleases.Columns["RLow"].DefaultCellStyle.Format = "N0";
            grvReleases.Columns["RLow"].HeaderText = "Từ số";
            grvReleases.Columns["RLow"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["RHigh"].DisplayIndex = 2;
            grvReleases.Columns["RHigh"].HeaderText = "Tới số";
            grvReleases.Columns["RHigh"].DefaultCellStyle.Format = "N0";
            grvReleases.Columns["RHigh"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["StartDate"].DisplayIndex = 3;
            grvReleases.Columns["StartDate"].HeaderText = "Phát hành";

            grvReleases.Columns["ExpireDate"].DisplayIndex = 4;
            grvReleases.Columns["ExpireDate"].HeaderText = "Hết hạn";

            grvReleases.Columns["Qtty"].DisplayIndex = 5;
            grvReleases.Columns["Qtty"].HeaderText = "Số lượng";
            grvReleases.Columns["Qtty"].DefaultCellStyle.Format = "N0";
            grvReleases.Columns["Qtty"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["ParValue"].DisplayIndex = 6;
            grvReleases.Columns["ParValue"].HeaderText = "Mệnh giá";
            grvReleases.Columns["ParValue"].DefaultCellStyle.Format = "N0";
            grvReleases.Columns["ParValue"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grvReleases.Columns["TotalValue"].DisplayIndex = 7;
            grvReleases.Columns["TotalValue"].HeaderText = "Giá trị";
            grvReleases.Columns["TotalValue"].DefaultCellStyle.Format = "N0";
            grvReleases.Columns["TotalValue"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grvReleases.Columns["Kind"].DisplayIndex = 8;
            grvReleases.Columns["Kind"].HeaderText = "Hình thức";
            grvReleases.Columns["Kind"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["Target"].DisplayIndex = 9;
            grvReleases.Columns["Target"].HeaderText = "Đối tượng";
            grvReleases.Columns["Target"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["Detail"].DisplayIndex = 10;
            grvReleases.Columns["Detail"].HeaderText = "Nội dung";
            grvReleases.Columns["Detail"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["Status"].DisplayIndex = 11;
            grvReleases.Columns["Status"].HeaderText = "Trạng thái";
            grvReleases.Columns["Status"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["Note"].DisplayIndex = 12;
            grvReleases.Columns["Note"].HeaderText = "Chú thích";
            grvReleases.Columns["Note"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grvReleases.Columns["ReleaseId"].DisplayIndex = 13;
            grvReleases.Columns["ReleaseId"].HeaderText = "Số hiệu";
            grvReleases.Columns["ReleaseId"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }

        private void grvReleases_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (grvReleases.SelectedRows.Count > 0)
            {
                SortableBindingList<ReleaseUI> releaseList =
                                                grvReleases.DataSource as SortableBindingList<ReleaseUI>;
                frmRelease frmRls = new frmRelease(releaseList[grvReleases.SelectedRows[0].Index], this);
                frmRls.ShowDialog();

            }
        }

        public void updateReleaseSummary()
        {
            grpStatistic.Visible = true;
            SortableBindingList<ReleaseUI> releaseList = grvReleases.DataSource as SortableBindingList<ReleaseUI>;
            if (releaseList != null)
            {
                long totalQtty = 0;
                long totalValue = 0;

                foreach (ReleaseUI item in releaseList)
                {
                    totalQtty += item.Qtty;
                    totalValue += Convert.ToInt64(item.ParValue * item.Qtty);
                }

                txtTotalQtty.Value = totalQtty;
                txtTotalValue.Value = totalValue;
            }
            else
            {
                txtTotalQtty.Value = 0;
                txtTotalValue.Value = 0;
            }
        }

        private void loadDetailSuggestion()
        {
            DALclient client = new DALclient();
            List<string> details = client.getDetailSuggest();
            if (details != null)
            {
                AutoCompleteStringCollection customSrc = new AutoCompleteStringCollection();
                foreach (string item in details)
                    customSrc.Add(item);
                txtDetail.AutoCompleteCustomSource = customSrc;
                txtDetail.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            }
        }

        private void loadTargetList()
        {
            if (cbTarget.Items.Count.Equals(0))
            {
                List<KeyValuePair<int, string>> targets = new List<KeyValuePair<int, string>>();
                cbTarget.Items.Clear();
                targets.Add(new KeyValuePair<int, string>(0, "Tất cả"));
                targets.Add(new KeyValuePair<int, string>((int)RTarget.CUSTOMER, "Khách hàng"));
                targets.Add(new KeyValuePair<int, string>((int)RTarget.PARTNER, "Đối tác"));
                targets.Add(new KeyValuePair<int, string>((int)RTarget.STAFF, "Nhân viên"));
                cbTarget.DataSource = targets;
                cbTarget.ValueMember = "Key";
                cbTarget.DisplayMember = "Value";
                cbTarget.SelectedIndex = 0;
            }

        }

        private void loadKindList()
        {
            if (cbKind.Items.Count.Equals(0))
            {
                List<KeyValuePair<int, string>> kinds = new List<KeyValuePair<int, string>>();
                cbKind.Items.Clear();
                kinds.Add(new KeyValuePair<int, string>(0, "Tất cả"));
                kinds.Add(new KeyValuePair<int, string>((int)RKind.SELL, "Bán"));
                kinds.Add(new KeyValuePair<int, string>((int)RKind.DISCOUNT, "Chiết khấu"));
                kinds.Add(new KeyValuePair<int, string>((int)RKind.GIFT, "Quà tặng"));
                cbKind.DataSource = kinds;
                cbKind.ValueMember = "Key";
                cbKind.DisplayMember = "Value";
                cbKind.SelectedIndex = 0;
            }
        }

        #region Release context menu

        private void mnCancelRelease_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvReleases.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = grvReleases.SelectedRows[0];
                    int releaseId = Convert.ToInt32(row.Cells["releaseId"].Value);

                    SortableBindingList<ReleaseUI> releaseList =
                                    grvReleases.DataSource as SortableBindingList<ReleaseUI>;
                    releaseList[row.Index].Status = Params.DISPOSED;

                    DALclient client = new DALclient();
                    client.disposelCouponByReleaseId(releaseId);
                    client.updateReleaseStatusById(releaseId, (int)RStatus.DISPOSED, Params.DISPOSED);

                    GlobalVars.ShowInfo("[ĐÃ HỦY] đợt phát hành: " + releaseSeries(releaseList[row.Index]));
                }
                else
                    GlobalVars.ShowWarning("[CHỌN] đợt phát hành trong danh sách.");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void mnDeleteRelease_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvReleases.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = grvReleases.SelectedRows[0];
                    int releaseId = Convert.ToInt32(row.Cells["releaseId"].Value);
                    SortableBindingList<ReleaseUI> releaseList =
                                    grvReleases.DataSource as SortableBindingList<ReleaseUI>;
                    releaseList[row.Index].Status = Params.DELETED;

                    DALclient client = new DALclient();
                    client.deleteCouponByReleaseId(releaseId);
                    client.updateReleaseStatusById(releaseId, (int)RStatus.DELETED, Params.DELETED);

                    GlobalVars.ShowInfo("[ĐÃ XÓA] đợt phát hành: " + releaseSeries(releaseList[row.Index]));
                }
                else
                    GlobalVars.ShowWarning("[CHỌN] đợt phát hành trong danh sách.");
            }
            catch
            {
                throw;
            }
        }

        private void mnDeleteReleaseDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvReleases.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = grvReleases.SelectedRows[0];
                    int releaseId = Convert.ToInt32(row.Cells["releaseId"].Value);
                    SortableBindingList<ReleaseUI> releaseList =
                                    grvReleases.DataSource as SortableBindingList<ReleaseUI>;

                    if (DialogResult.Yes == MessageBox.Show("[XÓA DỮ LIỆU] đợt phát hành: " + releaseSeries(releaseList[row.Index]) + "?", Params.CONFIRM, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        DALclient client = new DALclient();
                        client.deleteCouponByReleaseId(releaseId);
                        client.deleteReleaseById(releaseId);
                        releaseList.RemoveAt(grvReleases.SelectedRows[0].Index);
                        updateReleaseSummary();
                    }


                }
                else
                    GlobalVars.ShowWarning("[CHỌN] đợt phát hành trong danh sách.");
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError("ERROR: " + ex.Message);
            }
        }

        private string releaseSeries(ReleaseUI item)
        {
            return item.RCode + item.RLow.ToString() + "-" + item.RCode + item.RHigh.ToString();
        }

        #endregion

        #endregion

        #region Coupons
        public void updateCouponsList()
        {
            DALclient client = new DALclient();
            List<CouponUI> src = client.getCouponsByClaim(GlobalVars.activeUser,
                txtAlphaCode.Text + "-" +
                (txtNumCode.Value.Equals(0) ? string.Empty : txtNumCode.Value.ToString()),
                                        dtFrom.Value.Date, dtTo.Value.Date);
            if (src != null)
            {
                if (src.Count < 10000)
                {
                    SortableBindingList<CouponUI> cpList = new SortableBindingList<CouponUI>(src);
                    grvCoupons.DataSource = cpList;
                    formatCouponGrid(grvCoupons);
                }
                else
                {
                    btnCpReport_Click(null, null);
                }
            }
            else
                grvCoupons.DataSource = null;

            updateCouponsSummary(grvCoupons);
        }

        public void formatCouponGrid(DataGridView grv)
        {
            if (GlobalVars.activeRoles[0] == '0')
                return;

            grv.Columns["Serial"].HeaderText = "Mã số";
            grv.Columns["Serial"].DisplayIndex = 0;

            grv.Columns["StartDate"].HeaderText = "Phát hành";
            grv.Columns["StartDate"].DisplayIndex = 1;

            grv.Columns["ExpireDate"].HeaderText = "Hết hạn";
            grv.Columns["ExpireDate"].DisplayIndex = 2;

            grv.Columns["ParValue"].HeaderText = "Mệnh giá";
            grv.Columns["ParValue"].DisplayIndex = 3;
            grv.Columns["ParValue"].DefaultCellStyle.Format = "N0";

            grv.Columns["Status"].HeaderText = "Trạng thái";
            grv.Columns["Status"].DisplayIndex = 4;

            grv.Columns["ClaimBy"].HeaderText = "Thu hồi bởi";
            grv.Columns["ClaimBy"].DisplayIndex = 5;

            grv.Columns["ReleaseKind"].HeaderText = "Loại hình";
            grv.Columns["ReleaseKind"].DisplayIndex = 6;

            grv.Columns["ReleaseTarget"].HeaderText = "Đối tượng";
            grv.Columns["ReleaseTarget"].DisplayIndex = 7;

            grv.Columns["ReleaseDetail"].HeaderText = "Nội dung";
            grv.Columns["ReleaseDetail"].DisplayIndex = 8;

            grv.Columns["ClaimDate"].HeaderText = "Ngày thu hồi";
            grv.Columns["ClaimDate"].DisplayIndex = 9;

            grv.Columns["Note"].HeaderText = "Chú thích";
            grv.Columns["Note"].DisplayIndex = 10;

            grv.Columns["LastUpdated"].HeaderText = "Cập nhật";
            grv.Columns["LastUpdated"].DisplayIndex = 11;

            grv.Columns["CodeBase"].Visible = false;
            grv.Columns["CodeNumber"].Visible = false;
            grv.Columns["ReleaseName"].Visible = false;
            grv.Columns["ReleaseNote"].Visible = false;

            grv.Sort(grv.Columns["LastUpdated"], ListSortDirection.Descending);

        }

        private void dtCouponFrom_ValueChanged(object sender, EventArgs e)
        {
            updateCouponsList();
        }

        public void updateCouponsSummary(DataGridView grv)
        {
            grpStatistic.Visible = true;
            SortableBindingList<CouponUI> couponList = grv.DataSource as SortableBindingList<CouponUI>;
            if (couponList != null)
            {
                long totalQtty = 0;
                long totalValue = 0;

                foreach (CouponUI item in couponList)
                {
                    totalQtty++;
                    totalValue += Convert.ToInt64(item.ParValue);
                }
                txtTotalQtty.Value = totalQtty;
                txtTotalValue.Value = totalValue;
            }
            else
            {
                txtTotalQtty.Value = 0;
                txtTotalValue.Value = 0;
            }
        }

        private void resetSummary()
        {
            txtTotalQtty.Value = 0;
            txtTotalValue.Value = 0;
            grpStatistic.Visible = false;
        }

        private void grvCoupons_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (grvCoupons.SelectedRows.Count > 0)
                {
                    SortableBindingList<CouponUI> cpList =
                                                    grvCoupons.DataSource as SortableBindingList<CouponUI>;

                    frmCoupon frmCp = new frmCoupon(cpList[grvCoupons.SelectedRows[0].Index], this);
                    frmCp.ShowDialog();

                }
            }
            catch (System.Exception ex)
            {
                GlobalVars.ShowWarning("Hãy chọn một dòng trên danh sách.\n\n" + ex.Message);
            }

        }

        private void btnLocate_Click(object sender, EventArgs e)
        {
            frmCouponLocator frmLocator = new frmCouponLocator(this);
            frmLocator.ShowDialog();
        }

        private void btnCpReport_Click(object sender, EventArgs e)
        {
            List<CouponBriefUI> src = new List<CouponBriefUI>();
            DALclient client = new DALclient();
            src = client.reportClaimedCouponsByUser(GlobalVars.activeUser, dtFrom.Value.Date, dtTo.Value.Date);

            if (src != null)
            {
                SortableBindingList<CouponBriefUI> list = new SortableBindingList<CouponBriefUI>(src);
                grvCoupons.DataSource = list;
                formatCouponBrief(grvCoupons);
            }
            else
                grvCoupons.DataSource = null;

            updateCouponBriefSummary(grvCoupons);
        }



        #endregion

        #region Util
        private int getNearestRole(int role)
        {
            int retVal = -1;
            if (!string.IsNullOrEmpty(GlobalVars.activeUser) || !string.IsNullOrEmpty(GlobalVars.activeRoles))
            {
                string roles = GlobalVars.activeRoles;
                if (role > 0 && role < GlobalVars.activeRoles.Length - 1)
                {
                    roles += GlobalVars.activeRoles.Substring(0, role);
                    if (role == GlobalVars.activeRoles.Length) role = 0;
                    for (int i = role + 1; i < roles.Length - 1; i++)
                    {
                        if (roles[i] == '1')
                        {
                            retVal = i % GlobalVars.activeRoles.Length;
                            break;
                        }
                    }
                }
            }
            return retVal;
        }

        public static DataTable GenericListToDataTable(object list)
        {
            DataTable dt = null;
            Type listType = list.GetType();
            if (listType.IsGenericType)
            {
                Type elementType = listType.GetGenericArguments()[0];
                dt = new DataTable(elementType.Name + "List");

                MemberInfo[] miArray = elementType.GetMembers(
                    BindingFlags.Public | BindingFlags.Instance);
                foreach (MemberInfo mi in miArray)
                {
                    if (mi.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo pi = mi as PropertyInfo;
                        dt.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else if (mi.MemberType == MemberTypes.Field)
                    {
                        FieldInfo fi = mi as FieldInfo;
                        dt.Columns.Add(fi.Name, fi.FieldType);
                    }
                }

                IList il = list as IList;
                foreach (object record in il)
                {
                    int i = 0;
                    object[] fieldValues = new object[dt.Columns.Count];
                    foreach (DataColumn c in dt.Columns)
                    {
                        MemberInfo mi = elementType.GetMember(c.ColumnName)[0];
                        if (mi.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo pi = mi as PropertyInfo;
                            fieldValues[i] = pi.GetValue(record, null);
                        }
                        else if (mi.MemberType == MemberTypes.Field)
                        {
                            FieldInfo fi = mi as FieldInfo;
                            fieldValues[i] = fi.GetValue(record);
                        }
                        i++;
                    }
                    dt.Rows.Add(fieldValues);
                }
            }
            return dt;
        }

        private void goToTab(string tabName)
        {
            for (int i = 0; i < tabMain.TabPages.Count; i++)
            {
                if (tabMain.TabPages[i].Name == tabName)
                {
                    tabMain.SelectedIndex = i;
                    break;
                }
            }
        }

        #endregion

        private void btnImport_Click(object sender, EventArgs e)
        {
            frmImportReleasedCoupon impReleaseData = new frmImportReleasedCoupon();
            impReleaseData.ShowDialog();
        }

        private void btnImportClaimData_Click(object sender, EventArgs e)
        {
            frmImportClaimedCoupon impClaimData = new frmImportClaimedCoupon();
            impClaimData.ShowDialog();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            frmDeleteReleasedCoupons frmDelete = new frmDeleteReleasedCoupons(this);
            frmDelete.ShowDialog();
        }

    }
}
